package engine.systems.ui.drawer
{
	import engine.classes.enumerations.SystemPriority;
	import engine.groups.Group;
	import engine.systems.update.GameSystem;
	
	
	public class DrawerSystem extends GameSystem
	{
		private var vars:Object;
		private var duration:Number;
		
		public function DrawerSystem()
		{
			super(DrawerNode, updateNode);
			
			this.priority = SystemPriority.UPDATE;
		}
		
		private function updateNode(node:DrawerNode, time:Number):void
		{
			if(node.drawer._invalidate)
			{
				node.drawer._invalidate = false;
				
				if(node.drawer.state == Drawer.OPENING_STATE)
				{
					duration 	= node.drawer.openingTime;
					vars 		= node.drawer.openingVars;
					
					if(!vars || isNaN(duration))
					{
						node.drawer._state = Drawer.CLOSED_STATE;
						return;
					}
					
					vars.onComplete = this.opened;
				}
				else
				{
					duration 	= node.drawer.closingTime;
					vars 		= node.drawer.closingVars;
					
					if(!vars || isNaN(duration))
					{
						node.drawer._state = Drawer.OPENED_STATE;
						return;
					}
					
					vars.onComplete = this.closed;
				}
				
				vars.onCompleteParams = [node];
				
				node.tween.to(node.spatial, duration, vars, node.drawer.state.toString());
			}
		}
		
		private function opened(node:DrawerNode):void
		{
			node.drawer._state = Drawer.OPENED_STATE;
			
			if(node.drawer.opened.numListeners > 0)
				node.drawer.opened.dispatch(node.entity);
		}
		
		private function closed(node:DrawerNode):void
		{
			node.drawer._state = Drawer.CLOSED_STATE;
			
			if(node.drawer.closed.numListeners > 0)
				node.drawer.closed.dispatch(node.entity);
		}
	}
}